package com.atguigu.exam.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.exam.entity.*;
import com.atguigu.exam.exception.ExamException;
import com.atguigu.exam.mapper.*;
import com.atguigu.exam.service.AIService;
import com.atguigu.exam.service.QuestionService;
import com.atguigu.exam.vo.AiGenerateRequestVo;
import com.atguigu.exam.vo.QuestionImportVo;
import com.atguigu.exam.vo.QuestionQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 题目Service实现类
 * 实现题目相关的业务逻辑
 */
@Slf4j
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionAnswerMapper questionAnswerMapper;
    @Autowired
    private QuestionChoiceMapper questionChoiceMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;
    @Autowired
    private AIService aiService;

    @Override
    public Page<Question> getQusetionList(Page<Question> questionPage, QuestionQueryVo queryVo) {
        return questionMapper.getQusetionnList(questionPage, queryVo);
    }

    @Override
    public void getQusetionListStream(Page<Question> questionPage, QuestionQueryVo queryVo) {
        Page<Question> pageQuestions = questionMapper.selectPage(questionPage, new LambdaQueryWrapper<Question>()
                .eq(queryVo.getCategoryId() != null, Question::getCategoryId, queryVo.getCategoryId())
                .eq(StringUtils.hasLength(queryVo.getDifficulty()), Question::getDifficulty, queryVo.getDifficulty())
                .eq(StringUtils.hasLength(queryVo.getType()), Question::getType, queryVo.getType())
                .like(StringUtils.hasLength(queryVo.getKeyword()), Question::getTitle, queryVo.getKeyword())
                .orderByDesc(Question::getCreateTime)
        );
        List<Question> questions = pageQuestions.getRecords();
        fillQuestionAnswerAndChoice(questions);
    }

    @Override
    public Question getQuestionById(Long id) {
        Question question = questionMapper.getQuestionById(id);
        new Thread(() ->{
            redisTemplate.opsForZSet().incrementScore("question:popular", id, 1);
        }).start();
        return question;
    }

    @Override
    public int addQuestion(Question question) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<Question>().eq(Question::getTitle, question.getTitle())
                .eq(Question::getType, question.getType()).eq(Question::getCategoryId, question.getCategoryId()));
        if (exists) {
            throw new ExamException(250, "该分类下已存在该问题");
        }
        int  questionResult = baseMapper.insert(question);
        Long questionId = question.getId();
        QuestionAnswer answer = question.getAnswer();
        answer.setQuestionId(questionId);
        int questionChoiceResult = -1;
        if ("CHOICE".equals(question.getType())) {
            List<QuestionChoice> choices = question.getChoices();
            if (!CollectionUtils.isEmpty(choices)) {
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < choices.size(); i++) {
                    QuestionChoice questionChoice = choices.get(i);
                    questionChoice.setQuestionId(questionId);
                    questionChoice.setSort(i);
                    if (questionChoice.getIsCorrect()) {
                        if (!stringBuffer.isEmpty()) {
                            stringBuffer.append(",");
                        }
                        stringBuffer.append((char) (65 + i));
                    }
                   questionChoiceResult = questionChoiceMapper.insert(questionChoice);
                }
                answer.setAnswer(stringBuffer.toString());
            }
        }
        int questionAnswerResult = questionAnswerMapper.insert(answer);
        return (questionResult > 0 && questionChoiceResult > 0 && questionAnswerResult > 0) ? 1 : 0;
    }

    @Override
    public void updateQuestion(Question question) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<Question>().eq(Question::getTitle, question.getTitle())
                .eq(Question::getType, question.getType()).eq(Question::getCategoryId, question.getCategoryId())
                .ne(Question::getId,question.getId()));
        if (exists) {
            throw new ExamException(250, "该问题已存在");
        }
        question.setUpdateTime(null);
        baseMapper.updateById(question);
        QuestionAnswer answer = question.getAnswer();
        if ("CHOICE".equals(question.getType())) {
            questionChoiceMapper.delete(new LambdaQueryWrapper<QuestionChoice>().eq(QuestionChoice::getQuestionId, question.getId()));

            List<QuestionChoice> choices = question.getChoices();
            if (!CollectionUtils.isEmpty(choices)) {
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < choices.size(); i++) {
                    QuestionChoice questionChoice = choices.get(i);
                    questionChoice.setId(null);
                    questionChoice.setCreateTime(null);
                    questionChoice.setUpdateTime(null);
                    if (questionChoice.getIsCorrect()) {
                        if (!stringBuffer.isEmpty()) {
                            stringBuffer.append(",");
                        }
                        stringBuffer.append((char) (65 + i));
                    }
                    questionChoiceMapper.insert(questionChoice);
                }
                answer.setAnswer(stringBuffer.toString());
            }
        }
        questionAnswerMapper.updateById(answer);

    }

    @Override
    public void deleteQuestion(Long id) {
        Long count = paperQuestionMapper.selectCount(new LambdaQueryWrapper<PaperQuestion>().eq(PaperQuestion::getQuestionId, id));
        if (count > 0) {
            throw new ExamException(250, "该题目存在于某个试卷中，不能删除");
        }
        baseMapper.deleteById(id);
        questionAnswerMapper.delete(new LambdaQueryWrapper<QuestionAnswer>().eq(QuestionAnswer::getQuestionId, id));
        questionChoiceMapper.delete(new LambdaQueryWrapper<QuestionChoice>().eq(QuestionChoice::getQuestionId, id));
    }

    @Override
    public List<Question> getPopularQuestions(Integer size) {
        List<Question> popularQuestions = new ArrayList<>();
        Set<Object> objects = redisTemplate.opsForZSet().reverseRange("question:popular", 0, -1);
        if (!CollectionUtils.isEmpty(objects)) {
            objects.forEach(object -> {
                Question question = baseMapper.selectById((long) object.hashCode());
                popularQuestions.add(question);
            });
        }
        Integer diff = size - popularQuestions.size();
        if (diff > 0) {
            List<Question> questions = baseMapper.selectList(new LambdaQueryWrapper<Question>().orderByDesc(Question::getCreateTime)
                    .notIn(objects.size() > 0, Question::getId, objects)
                    .last("limit " + diff));
            popularQuestions.addAll(questions);
        }
        return popularQuestions;
    }

    @Override
    public int batchAddQuestions(List<QuestionImportVo> questions) {
        if (CollectionUtils.isEmpty(questions)) {
            throw new ExamException(250, "没有导入任何题目，请检查数据");
        }
        int successCount = 0;
        for (QuestionImportVo questionVo : questions) {
            Question question = convertQuestionImportVoToQuestion(questionVo);
            int result = addQuestion(question);
            successCount += result;
        }
        return successCount;
    }

    @Override
    public List<QuestionImportVo> generateQuestionsByAi(AiGenerateRequestVo request) {
        //1.生成提示词
        String prompt = buildPrompt(request);
        //2.调用AI大模型
        String content = aiService.callAi(prompt);
        //3.解析结果
        int startIndex = content.indexOf("```json");
        int endIndex = content.lastIndexOf("```");
        //保证有数据，且下标正确！
        if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
            //获取真正结果
            String realResult = content.substring(startIndex+7,endIndex);
            System.out.println("realResult = " + realResult);
            JSONObject jsonObject = JSONObject.parseObject(realResult);
            JSONArray questions = jsonObject.getJSONArray("questions");
            List<QuestionImportVo> questionImportVoList = new ArrayList<>();
            for (int i = 0; i < questions.size(); i++) {
                //获取对象
                JSONObject questionJson = questions.getJSONObject(i);
                QuestionImportVo questionImportVo = new QuestionImportVo();
                questionImportVo.setTitle(questionJson.getString("title"));
                questionImportVo.setType(questionJson.getString("type"));
                questionImportVo.setMulti(questionJson.getBoolean("multi"));
                questionImportVo.setDifficulty(questionJson.getString("difficulty"));
                questionImportVo.setScore(questionJson.getInteger("score"));
                questionImportVo.setAnalysis(questionJson.getString("analysis"));
                questionImportVo.setCategoryId(request.getCategoryId());

                //选择题处理选项
                if ("CHOICE".equals(questionImportVo.getType())) {
                    JSONArray choices = questionJson.getJSONArray("choices");
                    List<QuestionImportVo.ChoiceImportDto> choiceImportDtoList = new ArrayList<>(choices.size());
                    for (int i1 = 0; i1 < choices.size(); i1++) {
                        JSONObject choicesJSONObject = choices.getJSONObject(i1);
                        QuestionImportVo.ChoiceImportDto choiceImportDto = new QuestionImportVo.ChoiceImportDto();
                        choiceImportDto.setContent(choicesJSONObject.getString("content"));
                        choiceImportDto.setIsCorrect(choicesJSONObject.getBoolean("isCorrect"));
                        choiceImportDto.setSort(choicesJSONObject.getInteger("sort"));
                        choiceImportDtoList.add(choiceImportDto);
                    }
                    questionImportVo.setChoices(choiceImportDtoList);
                }
                //答案 [判断题！ TRUE |FALSE  false true  f  t 是 否]
                questionImportVo.setAnswer(questionJson.getString("answer"));
                questionImportVoList.add(questionImportVo);
            }
            return questionImportVoList;
        }
        throw new RuntimeException("ai生成题目json数据结构错误，无法正常解析！数据为：%s".formatted(content));
    }

    /**
     * 构建发送给AI让AI出题的提示词
     */
    public String buildPrompt(AiGenerateRequestVo request) {
        StringBuilder prompt = new StringBuilder();

        prompt.append("请为我生成").append(request.getCount()).append("道关于【")
                .append(request.getTopic()).append("】的题目。\n\n");

        prompt.append("要求：\n");

        // 题目类型要求
        if (request.getTypes() != null && !request.getTypes().isEmpty()) {
            List<String> typeList = Arrays.asList(request.getTypes().split(","));
            prompt.append("- 题目类型：");
            for (String type : typeList) {
                switch (type.trim()) {
                    case "CHOICE":
                        prompt.append("选择题");
                        if (request.getIncludeMultiple() != null && request.getIncludeMultiple()) {
                            prompt.append("(包含单选和多选)");
                        }
                        prompt.append(" ");
                        break;
                    case "JUDGE":
                        prompt.append("判断题（**重要：确保正确答案和错误答案的数量大致平衡，不要全部都是正确或错误**） ");
                        break;
                    case "TEXT":
                        prompt.append("简答题 ");
                        break;
                }
            }
            prompt.append("\n");
        }

        // 难度要求
        if (request.getDifficulty() != null) {
            String difficultyText = switch (request.getDifficulty()) {
                case "EASY" -> "简单";
                case "MEDIUM" -> "中等";
                case "HARD" -> "困难";
                default -> "中等";
            };
            prompt.append("- 难度等级：").append(difficultyText).append("\n");
        }

        // 额外要求
        if (request.getRequirements() != null && !request.getRequirements().isEmpty()) {
            prompt.append("- 特殊要求：").append(request.getRequirements()).append("\n");
        }

        // 判断题特别要求
        if (request.getTypes() != null && request.getTypes().contains("JUDGE")) {
            prompt.append("- **判断题特别要求**：\n");
            prompt.append("  * 确保生成的判断题中，正确答案(TRUE)和错误答案(FALSE)的数量尽量平衡\n");
            prompt.append("  * 不要所有判断题都是正确的或都是错误的\n");
            prompt.append("  * 错误的陈述应该是常见的误解或容易混淆的概念\n");
            prompt.append("  * 正确的陈述应该是重要的基础知识点\n");
        }

        prompt.append("\n请严格按照以下JSON格式返回，不要包含任何其他文字：\n");
        prompt.append("```json\n");
        prompt.append("{\n");
        prompt.append("  \"questions\": [\n");
        prompt.append("    {\n");
        prompt.append("      \"title\": \"题目内容\",\n");
        prompt.append("      \"type\": \"CHOICE|JUDGE|TEXT\",\n");
        prompt.append("      \"multi\": true/false,\n");
        prompt.append("      \"difficulty\": \"EASY|MEDIUM|HARD\",\n");
        prompt.append("      \"score\": 5,\n");
        prompt.append("      \"choices\": [\n");
        prompt.append("        {\"content\": \"选项内容\", \"isCorrect\": true/false, \"sort\": 1}\n");
        prompt.append("      ],\n");
        prompt.append("      \"answer\": \"TRUE或FALSE(判断题专用)|文本答案(简答题专用)\",\n");
        prompt.append("      \"analysis\": \"题目解析\"\n");
        prompt.append("    }\n");
        prompt.append("  ]\n");
        prompt.append("}\n");
        prompt.append("```\n\n");

        prompt.append("注意：\n");
        prompt.append("1. 选择题必须有choices数组，判断题和简答题设置answer字段\n");
        prompt.append("2. 多选题的multi字段设为true，单选题设为false\n");
        prompt.append("3. **判断题的answer字段只能是\"TRUE\"或\"FALSE\"，请确保答案分布合理**\n");
        prompt.append("4. 每道题都要有详细的解析\n");
        prompt.append("5. 题目要有实际价值，贴近实际应用场景\n");
        prompt.append("6. 严格按照JSON格式返回，确保可以正确解析\n");

        // 如果只生成判断题，额外强调答案平衡
        if (request.getTypes() != null && request.getTypes().equals("JUDGE") && request.getCount() > 1) {
            prompt.append("7. **判断题答案分布要求**：在").append(request.getCount()).append("道判断题中，");
            int halfCount = request.getCount() / 2;
            if (request.getCount() % 2 == 0) {
                prompt.append("请生成").append(halfCount).append("道正确(TRUE)和").append(halfCount).append("道错误(FALSE)的题目");
            } else {
                prompt.append("请生成约").append(halfCount).append("-").append(halfCount + 1).append("道正确(TRUE)和约").append(halfCount).append("-").append(halfCount + 1).append("道错误(FALSE)的题目");
            }
        }

        return prompt.toString();
    }
    private Question convertQuestionImportVoToQuestion(QuestionImportVo questionVo) {
        Question question = new Question();
        BeanUtils.copyProperties(questionVo,question);
        QuestionAnswer answer = new QuestionAnswer();
        if ("JUDGE".equals(questionVo.getType())) {
            answer.setAnswer(questionVo.getAnswer().toUpperCase());
        }else {
            answer.setAnswer(questionVo.getAnswer());
        }
        answer.setKeywords(questionVo.getKeywords());
        question.setAnswer(answer);
        if ("CHOICE".equals(questionVo.getType())) {
            List<QuestionImportVo.ChoiceImportDto> choices = questionVo.getChoices();
            List<QuestionChoice> questionChoices = new ArrayList<>();
            if (!CollectionUtils.isEmpty(choices)) {
                choices.forEach(choice -> {
                    QuestionChoice questionChoice = new QuestionChoice();
                    BeanUtils.copyProperties(choice,questionChoice);
                    questionChoices.add(questionChoice);
                });
            }
            question.setChoices(questionChoices);
        }
        return question;
    }

    private void fillQuestionAnswerAndChoice(List<Question> questions) {
        if (!CollectionUtils.isEmpty(questions)) {
            List<Long> questionIds = questions.stream().map(Question::getId).collect(Collectors.toList());
            List<QuestionAnswer> questionAnswers = questionAnswerMapper.selectList(new LambdaQueryWrapper<QuestionAnswer>()
                    .in(QuestionAnswer::getQuestionId, questionIds)
            );
            List<QuestionChoice> questionChoices = questionChoiceMapper.selectList(new LambdaQueryWrapper<QuestionChoice>()
                    .in(QuestionChoice::getQuestionId, questionIds)
            );
            Map<Long, QuestionAnswer> questionAnswerMap = questionAnswers.stream().collect(Collectors.toMap(
                    QuestionAnswer::getQuestionId,
                    questionAnswer -> questionAnswer
            ));
            Map<Long, List<QuestionChoice>> questionChoicesMap = questionChoices.stream().collect(Collectors.groupingBy(QuestionChoice::getQuestionId));
            questions.forEach(question -> {
                question.setAnswer(questionAnswerMap.get(question.getId()));
                if ("CHOICE".equals(question.getType())) {
                    List<QuestionChoice> choices = questionChoicesMap.get(question.getId());
                    if (!CollectionUtils.isEmpty(choices)) {
                        choices.sort(Comparator.comparing(QuestionChoice::getSort));
                        question.setChoices(choices);
                    }
                }
            });
        }
    }
}